<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>销售箱量分布</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="所属部门">
              <a-tree-select
                class="selectInputWidth"
                v-model="searchForm.deptId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :load-data="onLoadData"
                :tree-data="deptTreeData"
                placeholder="请选择"
                @change="onChangeTree"
              ></a-tree-select>
            </a-form-item>
            <a-form-item label="所属销售">
              <a-select v-model="searchForm.sellerId" class="selectInputWidth">
                <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="日期">
              <a-range-picker :value="rangeDate" @change="onDateChange">
                <a-icon slot="suffixIcon" type="calendar" />
              </a-range-picker>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出Excel</a-button>
            </a-form-item>
          </a-form>

          <a-table
            :loading="loading"
            :columns="columns"
            :data-source="tableData"
            class="tableMargin"
            :scroll="{x: 1800}"
            bordered
            :pagination="pagination"
            :rowKey="(v, i) => i"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { querySalesContainerAnalysisList } from '@/api/salesCenter'
import { querySellerDown, queryDeptDown } from '@/api'
import { commonExport } from '@/api/request'

const deptData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 1, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}

export default {
  data () {
    const columns = [
      {
        title: '序号',
        width: 70,
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '销售姓名',
        dataIndex: 'seller',
        width: 120
      },
      {
        title: '所属部门',
        dataIndex: 'department'
      },
      {
        title: '总箱量',
        dataIndex: 'orderQuantity'
      },
      {
        title: '总客户数',
        dataIndex: 'custQuantity'
      },
      {
        title: '客户活跃度',
        children: [
          {
            title: '总单数',
            dataIndex: 'custQuantityTotal'
          },
          {
            title: '5~10单客户数',
            dataIndex: 'custQuantity5to10'
          },
          {
            title: '＞10单客户数',
            dataIndex: 'custQuantityOver10'
          }
        ]
      },
      {
        title: '客户箱量分布',
        children: [
          {
            title: '<20',
            dataIndex: 'containerQuantityBelow20'
          },
          {
            title: '20~50',
            dataIndex: 'containerQuantity20To50'
          },
          {
            title: '51~100',
            dataIndex: 'containerQuantity50To100'
          },
          {
            title: '101~200',
            dataIndex: 'containerQuantity100To200'
          },
          {
            title: '201~500',
            dataIndex: 'containerQuantity200To500'
          },
          {
            title: '>500',
            dataIndex: 'containerQuantityOver500'
          }
        ]
      }
    ]
    return {
      loading: false,
      sellers: [],
      searchForm: {
        startDate: '', // 开始时间
        endDate: '', // 结束时间
        sellerId: null,
        deptId: null
      },
      columns,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      deptTreeData: []
    }
  },
  computed: {
    rangeDate () {
      return this.searchForm.startDate ? [moment(this.searchForm.startDate), moment(this.searchForm.endDate)] : null
    }
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      return new Promise((resolve, reject) => {
        queryDeptDown(e).then(rsp => {
          let initData = []
          rsp.data.forEach((value, index) => {
            initData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId
            })
          })
          this.deptTreeData = initData
          this.searchForm.deptId = rsp.data[0].deptId
          resolve()
        })
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      return new Promise((resolve) => {
        querySellerDown({ ...sellerData, deptId }).then(rsp => {
          this.sellers = rsp.data.map((v, i) => {
            if (!v.uiId) {
              v.name = '请选择'
              v.uiId = ''
            }
            return v
          })
          this.searchForm.sellerId = rsp.data[0].uiId
          resolve()
        })
      })
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      querySalesContainerAnalysisList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
        .then(rsp => {
          this.isFirstEnd = false
          this.loading = false
          this.tableData = rsp.data.list
          this.pagination = {
            current: this.pageNum,
            pageSize: rsp.data.pageSize,
            total: rsp.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              this.handleSubmit()
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              this.handleSubmit()
            }
          }
        }).catch(() => {
          this.loading = false
        })
    },
    onDateChange (date, dataStr) {
      this.searchForm.startDate = dataStr[0]
      this.searchForm.endDate = dataStr[1]
    },
    exportExcel () {
      commonExport('/sales/exportSalesContainerAnalysisList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: [
          {
            title: '销售姓名',
            dataIndex: 'seller'
          },
          {
            title: '所属部门',
            dataIndex: 'department'
          },
          {
            title: '总箱量',
            dataIndex: 'orderQuantity'
          },
          {
            title: '总客户数',
            dataIndex: 'custQuantity'
          },
          {
            title: '客户活跃度(总单数)',
            dataIndex: 'custQuantityTotal'
          },
          {
            title: '客户活跃度(5~10单客户数)',
            dataIndex: 'custQuantity5to10'
          },
          {
            title: '客户活跃度(＞10单客户数)',
            dataIndex: 'custQuantityOver10'
          },
          {
            title: '客户箱量分布(<20)',
            dataIndex: 'containerQuantityBelow20'
          },
          {
            title: '客户箱量分布(20~50)',
            dataIndex: 'containerQuantity20To50'
          },
          {
            title: '客户箱量分布(51~100)',
            dataIndex: 'containerQuantity50To100'
          },
          {
            title: '客户箱量分布(101~200)',
            dataIndex: 'containerQuantity100To200'
          },
          {
            title: '客户箱量分布(201~500)',
            dataIndex: 'containerQuantity200To500'
          },
          {
            title: '客户箱量分布(>500)',
            dataIndex: 'containerQuantityOver500'
          }
        ]
      })
    }
  },
  mounted () {
    const a = moment().startOf('month')
    const b = moment()
    // 所属部门
    // 所属销售
    Promise.all([this.initDept(deptData), this.initSellerDown()]).then(result => {
      const timeFormat = 'YYYY-MM-DD'
      this.searchForm.startDate = a.format(timeFormat)
      this.searchForm.endDate = b.format(timeFormat)
      this.handleSubmit()
    })
  }
}
</script>
